﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace GuidingRobot
{
    public class SerialComm : ISerialComm
    {
        private SerialPort SPort;


        /// <summary>
        /// 默认构造函数,（默认：COM3，9600，e，8，1）
        /// </summary>
        public SerialComm()
        {
            SPort = new SerialPort();
            SPort.PortName = "COM3";
            SPort.BaudRate = 9600;
            SPort.Parity = Parity.None;
            SPort.DataBits = 8;
            SPort.StopBits = StopBits.One;
            SPort.ReadBufferSize = 4096;
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="COM">COM口，如"COM1"</param>
        /// <param name="BaudRate">波特率如9600</param>
        public SerialComm(string COM, int BaudRate)
        {
            SPort = new SerialPort();
            SPort.PortName = COM;
            SPort.BaudRate = BaudRate;
            SPort.Parity = Parity.None;
            SPort.DataBits = 8;
            SPort.StopBits = StopBits.One;
            SPort.ReadBufferSize = 4096;
        }


        /// <summary>
        /// 实现ISerialComm接口的WritePort方法用来实现将byte数组写入串口
        /// </summary>
        /// <param name="bytesend">bytesend是要发送的数据</param>
        public void WritePort(byte[] bytesend)
        {
            if (SPort.IsOpen == false)
            {
                SPort.Open();
            }
            SPort.Write(bytesend, 0, bytesend.Length);
            SPort.Close();
        }
    }
}
